package com.kc.gb.device.plugins.strip.driver;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Timer;

/**
 * 灯带驱动程序
 */
@Slf4j
public class AtopControl {

    public String Ip;
    public int Port;
    public Socket socket = null;
    OutputStream outputStream = null;
    public boolean IsConnect = false;
    Thread t_reacive = null;
    AtopControlReceiveData ReceiveThread = null;
    public String StatusMsg = "";
    Timer timer = new Timer();

    /**
     * 关闭旧链接
     */
    public void CloseCurSocket() {
        try {
            if (socket != null) {
                if (!socket.isClosed()) {
                    socket.shutdownInput();
                }
                if (!socket.isClosed()) {
                    socket.shutdownOutput();
                }
                if (!socket.isClosed()) {
                    socket.close();
                }
            }

        } catch (IOException e) {
            log.error("AtopControl CloseCurSocket:{}",e.getMessage(),e);
        }
    }

    /**
     * 清空旧链接后进行硬件重连
     */
    public void RecreateCurSocket() throws IOException {
        try {
            log.info("AtopControl socket ip:{},port:{}", Ip, Port);
            CloseCurSocket();
            //socket = new Socket(Ip, Port);
            // 设置连接超时时间为 3 秒
            socket = new Socket();
            socket.connect(new InetSocketAddress(Ip, Port), 3000);
            IsConnect = socket.isConnected();
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            IsConnect = false;
            outputStream = null;
            log.error("AtopControl socket error:{}", e.getMessage(),e);
            throw e;
        }
    }

    public void Close() {
        try {
            IsConnect = false;
            if (timer != null) {
                timer.cancel();
            }
            if (t_reacive != null) {
                if (ReceiveThread != null) {
                    ReceiveThread.IsClose = true;
                }
                t_reacive.interrupt();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            CloseCurSocket();

        } catch (IOException e) {
            IsConnect = false;
            outputStream = null;
            log.error("AtopControl close socket connection error", e);
        }

    }

    public void Init() throws IOException {
        RecreateCurSocket();
        //接收控制器返回信息
        if (IsConnect) {
            ReceiveThread = new AtopControlReceiveData();
            ReceiveThread.atopItem = this;
            t_reacive = new Thread(ReceiveThread, Ip);     // 实例化Thread对象
            t_reacive.setDaemon(true); // 此线程在后台运行
            t_reacive.start(); // 启动线程
        }

        // 健康检查
        if (IsConnect) {
            CheckControlTask p_check_item = new CheckControlTask();
            p_check_item.atopItem = this;
            timer.schedule(p_check_item, 1000, 8000);
        }
    }

    public String DiagResult(int[] ccb_data) {
        int k, tmp, maxid;
        String tagstr = "";
        tagstr = "";
        tmp = 0;
        maxid = 0;

        for (k = 1; k <= 250; k++) {
            if ((k - 1) % 8 == 0) {
                tmp = ccb_data[3 + (k - 1) / 8];
            }
            if (tmp % 2 != 1) {
                maxid = k;
                tagstr = tagstr + "1";
            } else {
                tagstr = tagstr + "0";
            }
            tmp = tmp / 2;
        }

        tagstr = tagstr.substring(0, maxid);

        return tagstr;
    }

    //标签自检
    public void CheckAlltag() {

        try {
            byte[] bytes = new byte[7];
            bytes[0] = 7;//数据长度
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6] = 9;
            outputStream.write(bytes);

        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    //蜂鸣(普通标签)
    public void AB_BUZ_On(byte p_addr, Boolean ison) {
        try {
            if (ison) {
                byte[] bytes = new byte[8];
                bytes[0] = 8;//数据长度
                bytes[1] = 0;
                bytes[2] = 96;
                bytes[6] = 4;
                bytes[7] = p_addr;
                outputStream.write(bytes);
            } else {
                byte[] bytes = new byte[8];
                bytes[0] = 8;//数据长度
                bytes[1] = 0;
                bytes[2] = 96;
                bytes[6] = 5;
                bytes[7] = p_addr;
                outputStream.write(bytes);
            }

        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    //设置标签模式
    public void AB_TAG_mode(byte p_addr, byte buttontypes) {
        try {
            byte[] bytes = new byte[10];
            bytes[0] = 10;//数据长度
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6] = 31;
            bytes[7] = p_addr;
            bytes[8] = 3;
            bytes[9] = buttontypes;
            outputStream.write(bytes);
        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    //设置计数位
    public void AB_TAG_CountDigit(byte p_addr, byte p_count) {
        try {
            byte[] bytes = new byte[9];
            bytes[0] = 9;//数据长度
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6] = 30;
            bytes[7] = p_addr;
            bytes[8] = p_count;
            outputStream.write(bytes);
        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    //设置灯色
    public void AB_LED_Status(byte p_addr, byte p_color, byte p_status) {
        try {
            byte[] bytes = new byte[10];
            bytes[0] = 10;//数据长度
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6] = 31;
            bytes[7] = p_addr;
            bytes[8] = 0;
            bytes[9] = p_color;
            outputStream.write(bytes);
            //设置灯的状态
            bytes[8] = 4;
            bytes[9] = p_status;
            outputStream.write(bytes);
        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    //熄灭标签
    public void TagClear(byte p_addr) {
        try {
            byte[] bytes = new byte[8];
            bytes[0] = 8;//数据长度
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6] = 1;
            bytes[7] = p_addr;
            outputStream.write(bytes);

        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    public synchronized void AB_LED_Strip_DSP(byte p_addr,byte saddr,byte eaddr,byte p_color,byte p_status)
    {
        try {
            byte[] bytes=new byte[13];
            bytes[0] = 13;
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6]= 0x41;
            bytes[7]= p_addr;

            bytes[8]= 2;
            bytes[9]= saddr;
            bytes[10]=eaddr;
            bytes[11]=p_color;
            bytes[12]=p_status;
            //bytes[11]=16;
            //bytes[12]=0;
            outputStream.write(bytes);
        }
        catch (IOException e) {
            IsConnect=false;
            e.printStackTrace();
        }
    }

    //AT80C,AT70C-蜂鸣
    public void AB_AHA_BUZ_On(byte p_addr, byte p_BuzzerType, byte p_count) {
        try {
            if (p_count > 0 && (p_BuzzerType >= 2 && p_BuzzerType <= 5)) {
                byte[] bytes = new byte[10];
                bytes[0] = 10;//数据长度
                bytes[1] = 0;
                bytes[2] = 96;
                bytes[6] = 4;
                bytes[7] = p_addr;
                bytes[8] = p_BuzzerType;
                bytes[9] = p_count;
                outputStream.write(bytes);
            } else {
                byte[] bytes = new byte[9];
                bytes[0] = 9;//数据长度
                bytes[1] = 0;
                bytes[2] = 96;
                bytes[6] = 4;
                bytes[7] = p_addr;
                bytes[8] = p_BuzzerType;
                outputStream.write(bytes);
            }
        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    //显示字符串（AT80C）
    public void AB_LBC_DspStr(byte p_addr, String p_str) {
        try {

            if (p_str.length() < 12) {
                int p_length = p_str.length();
                for (int i = 0; i < (12 - p_length); i++) {
                    p_str = " " + p_str;
                }
            }
            if (p_str.length() > 12) {
                p_str = p_str.substring(0, 12);
            }
            System.out.println(p_str);
            char[] strChar = p_str.toCharArray();


            byte[] bytes = new byte[20];
            bytes[0] = 20;//数据长度
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6] = 0;
            bytes[7] = p_addr;
            for (int i = 0; i < 12; i++) {
                bytes[8 + i] = (byte) strChar[i];
            }


            outputStream.write(bytes);
        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    //显示字符串（AT70C）
    public void AT70C_AB_LBC_DspStr(byte p_addr, String p_str) {
        try {
            TagClear(p_addr);
            if (p_str.length() < 12) {
                int p_length = p_str.length();
                for (int i = 0; i < (12 - p_length); i++) {
                    p_str = " " + p_str;
                }
            }
            if (p_str.length() > 12) {
                p_str = p_str.substring(0, 12);
            }
            System.out.println(p_str);
            char[] strChar = p_str.toCharArray();


            byte[] bytes = new byte[21];
            bytes[0] = 21;//数据长度
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6] = 0;
            bytes[7] = p_addr;
            bytes[8] = 17;
            for (int i = 0; i < 12; i++) {
                bytes[9 + i] = (byte) strChar[i];
            }


            outputStream.write(bytes);
        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }

    //显示字符串（普通标签）
    public void AB_LB_DspStr(byte p_addr, String p_str) {
        try {
            if (p_str.length() < 6) {
                int p_length = p_str.length();
                for (int i = 0; i < (6 - p_length); i++) {
                    p_str = " " + p_str;
                }
            }
            if (p_str.length() > 6) {
                p_str = p_str.substring(0, 6);
            }
            System.out.println(p_str);
            char[] strChar = p_str.toCharArray();


            byte[] bytes = new byte[15];
            bytes[0] = 15;//数据长度
            bytes[1] = 0;
            bytes[2] = 96;
            bytes[6] = 0;
            bytes[7] = p_addr;

            for (int i = 0; i < 6; i++) {
                bytes[8 + i] = (byte) strChar[i];
            }

            bytes[14] = 0;//小数位

            outputStream.write(bytes);
        } catch (IOException e) {
            IsConnect = false;
            e.printStackTrace();
        }
    }
}

